package org.trinity.netdisk.util;

import org.apache.catalina.connector.ClientAbortException;

import javax.servlet.ServletOutputStream;
import java.io.IOException;
import java.util.Calendar;

public class RateLimitBuffer {
    private final byte[] buff;
    private Long beforeRead;

    public RateLimitBuffer(int bufferSize) {
        buff = new byte[bufferSize];
    }

    public byte[] getBuff() {
        beforeRead = Calendar.getInstance().getTime().getTime();
        return buff;
    }

    public void read(ServletOutputStream outputStream) throws IOException {
        try {
            outputStream.write(this.getBuff());
        }
        //无视连接断开异常
        catch (ClientAbortException ignored) {}

        long afterRead = Calendar.getInstance().getTime().getTime();
        if (afterRead - beforeRead >= 1000) {
            return;
        }
        try {
            Thread.sleep(1000 - afterRead + beforeRead);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
